#include "tcpthread.h"
#include <QTcpSocket>
TcpThread::TcpThread(QObject *parent)
    : QThread{parent},m_ip(""),m_port(0),m_socket(nullptr)
{
    
}

TcpThread::~TcpThread()
{
    if (m_socket)
    {
        m_socket->abort();
        delete m_socket;
        m_socket = nullptr;
    }
    quit();
    wait();
}

void TcpThread::setServer(const QString& ip, quint16 port)
{
    this->m_ip = ip;
    this->m_port = port;
}

void TcpThread::send(const QByteArray& data)
{
    emit sendData(data); // 触发信号
    
}

void TcpThread::run()
{
    m_socket = new QTcpSocket();

    connect(m_socket, &QTcpSocket::connected, this, &TcpThread::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpThread::onDisconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpThread::onReadyRead);
    connect(this, &TcpThread::sendData, this, &TcpThread::onSendData, Qt::QueuedConnection);
    qDebug() << "Connecting to" << m_ip << ":" << m_port;
    m_socket->connectToHost(m_ip, m_port);

    if (!m_socket->waitForConnected(5000)) {
        qWarning() << "Connection timeout:" << m_socket->errorString();
    }


    exec(); // 启动线程的消息循环
}

void TcpThread::onReadyRead()
{
    qDebug() << "TcpThread::onReadAll" << QThread::currentThreadId();
    QByteArray data = m_socket->readAll();
    emit readyRead(data);

}
void TcpThread::onConnected()
{
    emit connected();
}

void TcpThread::onDisconnected()
{
    emit disconnected();
}

void TcpThread::onSendData(QByteArray data)
{
    if (m_socket && m_socket->state() == QAbstractSocket::ConnectedState) {
        qDebug() << "TcpThread::onSendData" << QThread::currentThreadId();
        m_socket->write(data);
        m_socket->flush(); // 确保立即发送
    }
    else {
        qWarning() << "Socket not connected. Cannot send data.";
    }
}
